package com.example.ecommercedemo.controller;

import com.auth0.jwt.JWT;
import com.example.ecommercedemo.entity.User;
import com.example.ecommercedemo.entity.VO.LoginUser;
import com.example.ecommercedemo.service.UserService;
import com.example.ecommercedemo.utils.JWTUtils;
import com.example.ecommercedemo.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @PostMapping("/login") //登录
    public ServerResponse<String> login(@RequestBody LoginUser loginUser){
        //先判断验证码是否正确
        //1如何从Redis取出保存的验证码
        String storeCode= (String) redisTemplate.opsForValue().get("captcha_codes:"+loginUser.getUuid());
        System.out.println(storeCode+loginUser.toString());
        if(loginUser.getCode().equals(storeCode)){
            User u=userService.getUser(loginUser);
            if(u!=null){//比对账号和密码
                Map<String,String> map=new HashMap<>();
                map.put("userid",u.getUserId()+"");
                map.put("username",u.getUserName());
                map.put("avatar", u.getAvatar()); // 添加头像信息
                String token= JWTUtils.getToken(map);
                redisTemplate.delete(storeCode);
                return ServerResponse.createBySuccess(200,token,"登陆成功");
            }
            return ServerResponse.createByFail(500,"账号或密码错误");
        }else{
            return ServerResponse.createByFail(500,"验证码错误");
        }
    }
    @GetMapping("/getInfo")
    public ServerResponse<User> getInfo(HttpServletRequest request) {
        //如何根据token获取用户的信息id
        String token = request.getHeader("Authorization");
        System.out.println(token + " ");
        String id = JWT.decode(token.substring(token.lastIndexOf(" ") + 1)).getClaim("userid").asString();
        User user = userService.getUserById(Integer.parseInt(id));

        return ServerResponse.createBySuccess(200, user, "查询成功");

    }}
